package com.fy.fyspace.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

/**
 * Bean拷贝工具类
 */
@Slf4j
public class BeanCopyUtils {

  /**
   * 拷贝对象属性
   *
   * @param source 源对象
   * @param clazz  目标对象类型
   * @return 目标对象
   */
  public static <V> V copyProperties(Object source, Class<V> clazz) {
    if (source == null) {
      return null;
    }
    V target = null;
    try {
      target = clazz.newInstance();
      BeanUtils.copyProperties(source, target);
    } catch (Exception e) {
      log.error("Bean拷贝失败", e);
    }
    return target;
  }

  /**
   * 拷贝对象列表属性
   *
   * @param sourceList 源对象列表
   * @param supplier   目标对象提供者
   * @return 目标对象列表
   */
  public static <T, V> List<V> copyListProperties(List<T> sourceList, Supplier<V> supplier) {
    if (sourceList == null || sourceList.isEmpty()) {
      return new ArrayList<>();
    }
    List<V> targetList = new ArrayList<>(sourceList.size());
    for (T source : sourceList) {
      V target = supplier.get();
      BeanUtils.copyProperties(source, target);
      targetList.add(target);
    }
    return targetList;
  }
}